﻿using System;
using System.Collections.Generic;
using System.IO;
using ALC.Core.Constants;
using ALC.Core.Helpers;
using MaterialDesignThemes.Wpf;
using WPFCommon.Logger;
using WPFCommon.ViewModels;
using WPFCommon.ViewModels.Base;
using WPFCommon.ViewModels.Logger;
using WPFCommon.ViewModels.Message;
using WPFCommon.ViewModels.Popup;

namespace ALC.Core.ViewModels.Message
{
    public class Logger : ViewModelBase
    {
        #region private members

        private FileLogger _plcLogger;

        private static Logger _instance = new Logger
        {
        };

        #endregion

        #region props

        public PopupLogger PopupLogger { get; private set; }

        public MessageQueueViewModel MessageQueueViewModel { get; set; }

        /// <summary>
        /// Used to prompt user when the machine state is changed
        /// </summary>
        public ISnackbarMessageQueue StateChangedMessageQueue { get; set; }


        public static Logger Instance
        {
            get { return _instance; }
        }

        #endregion

        #region ctor

        public Logger()
        {
            // State changed logging
            StateChangedMessageQueue = new SnackbarMessageQueue(TimeSpan.FromSeconds(3));

            var logPath = Path.Combine(DirectoryConstants.LogDir, "PlcLog.txt");
            _plcLogger = new FileLogger(TimeSpan.FromDays(3), logPath, 10000);
            _plcLogger.StartLogging();

            PopupLogger = new PopupLogger(TimeSpan.FromMilliseconds(200));
            PopupLogger.StartLogging();
            
            logPath = Path.Combine(DirectoryConstants.LogDir, "Misc.txt");
            MessageQueueViewModel = new MessageQueueViewModel(logPath, 20);
        }

        #endregion

        #region api

        public static void LogToUi(string displayMessage, string saveMessage)
        {
            Instance.MessageQueueViewModel.EnqueueItem(new LogItemViewModel()
            {
                DisplayMessage = displayMessage,
                SaveMessage = saveMessage,
                LogTime = DateTime.Now
            });
        }

        public static void LogPlc(string message)
        {
            Instance._plcLogger.EnqueueMessage(message);
        }

        public static void LogStateChanged(string message)
        {
            Instance.StateChangedMessageQueue.Enqueue(message);
        }

        public static void EnqueuePopup(PopupViewModel popupViewModel)
        {
            _instance.PopupLogger.EnqueuePopup(popupViewModel);
        }

        #endregion
    }
}